﻿var formcategoryUrl = urlRoot + '/psi/html/Psi_GoodsClass.html?n=' + Math.random();
var dicUrl = urlRoot + '../psi/html/Psi_Goods.html?n=' + Math.random();
var actionUrl = 'ashx/Psi_GoodsHandler.ashx';
var actionCategoryUrl = 'ashx/Psi_GoodsClassHandler.ashx';//分类

$(function () {
    var size = { width: $(window).width(), height: $(window).height() };
    mylayout.init(size);
    $(window).resize(function () {
        size = { width: $(window).width(), height: $(window).height() };
        mylayout.resize(size);
    });

    DicCategory.bindTree();//绑定分类
    autoResize({ dataGrid: '#userGrid', gridType: 'datagrid', callback: mygrid.databind, height: 4, width: 204 });

    $('#a_addCategory').click(DicCategory.addCategory);
    $('#a_delCategory').click(DicCategory.delCategory);
    $('#a_editCategory').click(DicCategory.editCategory);

    //字典数据
    $('#a_add').click(mygrid.add);
    $('#a_edit').click(mygrid.edit);
    $('#a_delete').click(mygrid.del);

    $('#a_search').click(function () {

        search.go('list');
    });
    $('#a_getSearch').click(function () {//自定义搜索框
        console.log("aa");
        mySearch();
    });

    $('#a_refresh').click(function () {
        var node = DicCategory.getSelected();
        if (node)
            mygrid.reload(node.id);
        else {
            msg.warning('请选择字典类别。');
        }
    });
});

var mylayout = {
    init: function (size) {
        $('#layout').width(size.width - 4).height(size.height - 4).layout();
        var center = $('#layout').layout('panel', 'center');
        center.panel({
            onResize: function (w, h) {
                $('#dicGrid').datagrid('resize', { width: w, height: h });
            }
        });
    },
    resize: function (size) {
        mylayout.init(size);
        $('#layout').layout('resize');
    }
};

var DicCategory = {
    bindTree: function () {
        $('#dataDicType').tree({
            url: 'ashx/Psi_GoodsClassHandler.ashx',
            onLoadSuccess: function (node, data) {
                if (data.length == 0) {
                    $('#noCategoryInfo').fadeIn();
                }

                $('body').data('categoryData', data);
            },
            onClick: function (node) {
                var cc = node.id;//得到节点ID
                $('#dicGrid').treegrid({
                    url: actionUrl,
                    queryParams: { goodsClassID: cc }
                });
            }
        });
    },
    reload: function () {
        $('#dataDicType').tree('reload');
    },
    getSelected: function () {
        return $('#dataDicType').tree('getSelected');
    },
    addCategory: function () {
        var addDialog = top.$.hDialog({
            title: '添加商品类别',
            iconCls: 'icon-add',
            href: formcategoryUrl,
            width: 400,
            height: 300,
            onLoad: function () {
                //top.$('#txt_sortnum').numberspinner({ min: 0, max: 999 });
            },
            submit: function () {
                var isValid = top.$('#uiform').form("validate");
                if (isValid) {
                    //$.ajaxjson(actionUrl, 'action=add&' + top.$('#dicCateForm').serialize(), function (d) {
                    var query = createParam('add', '0');
                    $.ajaxjson(actionCategoryUrl, query, function (d) {
                        if (parseInt(d) > 0) {
                            msg.ok('商品类别添加成功。');
                            addDialog.dialog('close');
                            DicCategory.reload();
                        } else {
                            MessageOrRedirect(d);
                        }
                    });
                }
            }
        });
    },
    editCategory: function () {
        var node = DicCategory.getSelected();
        if (node) {
            var editDialog = top.$.hDialog({
                title: '编辑商品类别',
                iconCls: 'icon-edit',
                href: formcategoryUrl,
                width: 400,
                height: 300,
                onLoad: function () {
                    top.$('#txt_className').textbox('setValue', node.text);
                    top.$('#txt_classNo').textbox('setValue', node.attributes.classNo);
                    top.$('#txt_note').val(node.attributes.note);
                    top.$('#txt_description').textbox('setValue', node.attributes.description);

                },
                submit: function () {
                    var isValid = top.$('#uiform').form("validate");
                    if (isValid) {
                        var query = createParam('edit', node.id);
                        $.ajaxjson(actionCategoryUrl, query, function (d) {
                            if (parseInt(d) > 0) {
                                msg.ok('商品类别编辑成功啦。');
                                editDialog.dialog('close');
                                DicCategory.reload();
                            } else {
                                MessageOrRedirect(d);
                            }
                        });
                    }
                }
            });
        } else {
            msg.warning('亲,请选择商品类别。');
        }
    },
    delCategory: function () {
        var node = DicCategory.getSelected();
        if (node) {
            if (confirm('确认要删除此类别吗?删除分类将通商品一起删除？')) {
                var query = createParam('delete', node.id);
                $.ajaxjson(actionCategoryUrl, query, function (d) {
                    if (parseInt(d) > 0) {
                        msg.ok('商品类别删除成功。');
                        DicCategory.reload();
                        mygrid.reload(node.id);//删除分类时刷新右侧表格
                    } else {
                        MessageOrRedirect(d);
                    }
                });
            }
        } else {
            msg.warning('亲,请选择商品类别。');
        }
    }
};





Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}


function createParam(action, keyid) {
    var o = {};
    var query = top.$('#uiform').serializeArray();
    query = convertArray(query);
    o.jsonEntity = JSON.stringify(query);
    o.action = action;
    o.keyid = keyid;
    return "json=" + JSON.stringify(o);
}
var dicDialog;
var mygrid = {
    databind: function (winSize) {
        $('#dicGrid').treegrid({
            toolbar: '#toolbar',
            title: "商品管理",
            iconCls: 'icon icon-list',
            width: winSize.width,
            height: winSize.height,
            nowrap: false, //折行
            rownumbers: true, //行号
            striped: true, //隔行变色
            idField: 'KeyId',//主键
            treeField: 'Title',
            showFooter: true,//显示页脚
            singleSelect: true, //单选
            frozenColumns: [[]],
            //单行变色
            rowStyler: function (value, row, index) {
                //var date = new Date();
                //var year = date.getFullYear();
                //var month = date.getMonth() + 1;
                //var day = date.getDate();
                //var hour = date.getHours();
                //var minute = date.getMinutes();
                //var second = date.getSeconds();
                //var mydatee = year + '/' + (month - 4) + '/' + day + ' ' + hour + ':' + minute + ':' + second;
                ////把字符串格式转化为日期类
                //if (value.up_time) {
                //    value.up_time = value.up_time.replace(/-/g, "/");
                //}
                //value.up_time = value.up_time.parseInt(value.up_time);
                //进行比较
                //var time2 = new Date().Format("yyyy/MM/dd hh:mm:ss");
                //var yy = time2.parseInt(time2);
                //console.log("格式化的时间" + time2);
                //time2 = time2.replace(/-/g, "/");
                //console.log("我的时间" + mydatee);
                if (value.up_time === '' || value.up_time === undefined || value.up_time === null) {
                    return 'background-color:pink;';
                } else {
                    //当前时间减掉5个月还大于更新时间
                    //console.log("我的时间" + mydatee);
                    var datett = new Date();//获取当前时间
                    var shi = datett.getFullYear();//获取当前时间年
                    var datat = parseInt(datett.getMonth() + 1 - 4);//获取当前时间月and减掉4个月,月从0开始所以加1
                    if (datat <= 0) {//如果当前时间月减掉4个月小于等于0
                        shi = datett.getFullYear() - 1;//当前时间年减1
                        if (datat == 0) {//如果当前时间月减掉的4个月等于0
                            datat = 12;//那么当前月等于12
                        } else {
                            datat = parseInt(12 - Math.abs(datat));//当前时间月等于n=12-(6+1-4),绝对值
                        }
                    }
                    var qq = shi + '/' + datat + '/' + datett.getDate() + ' ' + datett.getHours() + ':' + datett.getMinutes() + ':' + datett.getSeconds() + '.000';
                    var timestamp1 = parseInt(new Date(qq).getTime() / 1000);    // 当前时间戳
                    var date = value.up_time;//得到更新时间
                    //date = date.substring(0, 19);
                    date = date.replace(/-/g, '/');//正则替换斜杠
                    var timestamp2 = parseInt(new Date(date).getTime() / 1000); //更新时间时间戳
                    if (timestamp2 > timestamp1) {
                        //console.log("11111的时间" + yy);
                        //console.log("66666更新的时间" + value.up_time);
                        //return 'background-color:#ff9966;color:blue;';
                    } else {
                        //console.log("大家的时间" + yy);
                        //console.log("大家更新的时间" + value.up_time);
                        return 'background-color:pink;';
                    }
                }
            },

            columns: [[
                //{ title: 'ID', field: 'KeyId', width: 60 },
                { title: '编号', field: 'goodsNo', width: 140, sortable: true },
                { title: '名称', field: 'goodsName', width: 140, sortable: true },
                { title: '简称', field: 'goodsShortName', width: 80, sortable: true },
                { title: '分类', field: 'goodsClassName', width: 140, sortable: true },
                { title: '单位', field: 'unit', width: 50, sortable: true },
                { title: '规格', field: 'specs', width: 50, sortable: true },
                { title: '库存', field: 'stock', width: 70, sortable: true },
                {
                    title: '参考库存总额', field: 'stockall', width: 100, formatter: function (value, row, index) {
                        return (row.stock * row.buyPrice).toFixed(2);
                    }
                },
                { title: '进价', field: 'buyPrice', width: 70, sortable: true },
                { title: '售价', field: 'sellPrice', width: 70, sortable: true },
                { title: '状态', field: 'status', width: 70, sortable: true },
                { title: '更新时间', field: 'up_time', width: 160, sortable: true },

            ]],
            pagination: true,
            pageSize: PAGESIZE,
            pageList: [20, 50, 200, 1000]
        });
    },
    reload: function (cc) {
        $('#dicGrid').treegrid({
            url: actionUrl,
            queryParams: { goodsClassID: cc }
        });
    },
    GetSelectedRow: function () {
        return $('#dicGrid').treegrid('getSelected');
    },
    initCtrl: function (dicId) {

        var parentTree = top.$('#txt_goodsClassID').combotree({
            url: '/psi/ashx/Psi_GoodsClassHandler.ashx',
            valueField: 'id',
            textField: 'text',
            editable: false,
            onSelect: function (item) {
                top.$('#txt_goodsClassName').textbox('setValue', item.text);
            },
            onLoadSuccess: function () {
                var cnode = DicCategory.getSelected();
                if (cnode) {
                    top.$('#txt_goodsClassID').combotree('setValue', cnode.id);
                    top.$('#txt_goodsClassName').textbox('setValue', cnode.text);
                }
            }
        });

    },
    add: function () {

        if (!DicCategory.getSelected()) {
            msg.warning('请选择商品类别！');
            return false;
        }

        dicDialog = top.$.hDialog({
            href: '/psi/html/Psi_Goods.html',
            width: 400,
            height: 380,
            title: '添加商品',
            iconCls: 'icon-add',
            onLoad: function () {
                mygrid.initCtrl();
            },
            submit: function () {
                var query = createParam("add", 0);
                if (top.$('#uiform').form('validate')) {
                    $.ajaxjson(actionUrl, query, function (d) {
                        if (parseInt(d) > 0) {
                            msg.ok("商品添加成功！");
                            mygrid.reload(top.$('#txt_goodsClassID').combobox('getValue'));
                            dicDialog.dialog('close');//添加完关闭页面
                        } else {
                            MessageOrRedirect(d);
                        }
                    });
                }
            }
        });
    },
    edit: function () {
        var row = mygrid.GetSelectedRow();
        if (row == null) {
            msg.warning("请选择商品。");
            return false;
        }
        dicDialog = top.$.hDialog({
            href: dicUrl,
            width: 400,
            height: 380,
            title: '编辑商品',
            iconCls: 'icon-edit',
            onLoad: function () {
                mygrid.initCtrl(row.KeyId);
                top.$('#txt_goodsNo').textbox('setValue', row.goodsNo);
                top.$('#txt_goodsName').textbox('setValue', row.goodsName);
                top.$('#txt_goodsShortName').textbox('setValue', row.goodsShortName);
                top.$('#txt_specs').textbox('setValue', row.specs);
                top.$('#txt_unit').textbox('setValue', row.unit);

                top.$('#txt_stock').numberspinner({ readonly: true });//编辑的时候不允许修改库存
                top.$('#txt_stock').numberspinner('setValue', row.stock);
                top.$('#txt_buyPrice').numberbox('setValue', row.buyPrice);
                top.$('#txt_sellPrice').numberbox('setValue', row.sellPrice);
                top.$('#txt_status').combobox('setValue', row.status);
            },
            submit: function () {
                var query = createParam("edit", row.KeyId);
                if (top.$('#uiform').form('validate')) {
                    $.ajaxjson(actionUrl, query, function (d) {
                        if (parseInt(d) > 0) {
                            msg.ok(d.Message);
                            mygrid.reload(top.$('#txt_goodsClassID').combobox('getValue'));
                            dicDialog.dialog('close');
                        } else {
                            MessageOrRedirect(d);
                        }
                    });
                }
            }
        });
    },
    del: function () {
        var row = mygrid.GetSelectedRow();
        if (row) {
            if (confirm('确认要删除该商品吗?')) {
                var query = createParam("delete", row.KeyId);
                $.ajaxjson(actionUrl, query, function (d) {
                    if (parseInt(d) > 0) {
                        msg.ok("商品删除成功！");
                        var node = DicCategory.getSelected();
                        if (node)
                            mygrid.reload(node.id);
                    } else {
                        MessageOrRedirect(d);
                    }
                });
            }
        } else {
            msg.warning('请选中要删除的商品。');
        }
    }
}

//自定义搜索开始
function mySearch() {
    console.log("a");
    var myunit = $("#al").textbox('getValue');
    var query = '{"groupOp":"AND","rules":[],"groups":[]}';
    var o = JSON.parse(query);
    var i = 0;
    if (myunit != '' && myunit != undefined) {//假如单位搜索不为空
        o.rules[i] = JSON.parse('{"field":"goodsName","op":"cn","data":"' + myunit + '"}');
        i = i + 1;
    }

    $('#dicGrid').datagrid('reload', { filter: JSON.stringify(o) });
}